package ranab.gui;

import java.io.*;
import javax.swing.*;


/*
 * This class encapsulates <code>java.io</code>.
 * 
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
 */
public
class TextAreaIo {
    
	/**
     * Maximum number of characters in the text area to be written.
     * Currently it is 10k.
     */
    public final static int MAX_SIZE = 10240;
    
	/**
	 * Get <code>java.io.StringReader</code> object to read text area data.
	 */
	public static StringReader getReader(JTextArea area)  {
		return new StringReader(area.getText());
	}
	
	/**
	 * Get <code>java.io.InputStream</code> object to read text area data.
	 */
	public static DataInputStream getInputStream(JTextArea area)  {
		return new DataInputStream(new ByteArrayInputStream(area.getText().getBytes()));
	}
	
	/**
	 * Get <code>java.io.PrintWriter<code> object to write in the text area.
	 */
	public static PrintWriter getWriter(final JTextArea area)  {
		return new PrintWriter( new Writer()  {
				public void write(char[] cbuf, int off, int len) {
                    if(area.getText().length()>MAX_SIZE) {
                        area.setText("");
                    }
	        		area.append(new String(cbuf, off, len));
	    		}	
				
				public void close()  {
				}
				
				public void flush()  {
				}
			}
		);
	}
	
	/**
	 * Get <code>java.io.PrintStream</code> to write in the text area.
	 */
	public static PrintStream getOutputStream(final JTextArea area)  {
		return new PrintStream( new OutputStream()  {
				public void write(int b)  {
                    if(area.getText().length()>MAX_SIZE) {
                        area.setText("");
                    }
					String str = new String(new byte[]  {(byte)b}); 
					area.append(str);				
				}
				
				public void write(byte[] b, int off, int len)  {
                    if(area.getText().length()>MAX_SIZE) {
                        area.setText("");
                    }
					String str = new String(b, off, len);
					area.append(str);
				}
			}
		);
	}
}
